import 'dart:async';
import 'dart:io';
// 移除未使用/冗余导入，依赖 pd_log.dart 的导出
// import 'log_file_info.dart';
import '../pd_log.dart';
// import 'log_ledger.dart';
import 'file_events.dart';

/// 日志滚动策略枚举。
///
/// - [none]：不滚动，永久保留所有日志；
/// - [days]：按天数保留最近 N 天；
/// - [months]：按月数保留最近 N 个月；
/// - [years]：按年数保留最近 N 年。
enum LogRetentionStrategy { none, days, months, years }

/// 日志滚动工具，提供按配置删除过期日志的能力。
class LogRotation {
  /// 根据策略与数量，删除早于阈值的日志文件。
  ///
  /// 返回删除的文件数量。
  static Future<int> enforce({
    required LogRetentionStrategy strategy,
    required int count,
  }) async {
    if (strategy == LogRetentionStrategy.none || count <= 0) return 0;

    final logFiles = await PDLog.listLogFiles();
    // 先同步快照（为被删除文件保留最新状态）
    await LogLedger.syncFromFiles(logFiles);
    final now = DateTime.now();
    final cutoffMs = _computeCutoffMs(now, strategy, count);
    int deleted = 0;
    for (final f in logFiles) {
      if (f.modifiedMs > 0 && f.modifiedMs < cutoffMs) {
        try {
          final file = File(f.path);
          if (file.existsSync()) {
            await file.delete();
            deleted++;
            await LogLedger.recordDeletion(f.path);
            FileEventBus.instance.emitDeleted(f.path);
          }
        } catch (_) {
          // ignore deletion errors
        }
      }
    }
    // 再次同步剩余文件快照
    final after = await PDLog.listLogFiles();
    await LogLedger.syncFromFiles(after);
    return deleted;
  }

  static int _computeCutoffMs(
      DateTime now, LogRetentionStrategy strategy, int count) {
    DateTime cutoff;
    switch (strategy) {
      case LogRetentionStrategy.days:
        cutoff = now.subtract(Duration(days: count));
        break;
      case LogRetentionStrategy.months:
        cutoff = _subtractMonths(now, count);
        break;
      case LogRetentionStrategy.years:
        cutoff = DateTime(now.year - count, now.month, now.day);
        break;
      case LogRetentionStrategy.none:
        cutoff = now;
        break;
    }
    // 对齐到当天 00:00:00，避免边界时间戳抖动
    cutoff = DateTime(cutoff.year, cutoff.month, cutoff.day);
    return cutoff.millisecondsSinceEpoch;
  }

  /// 减去 N 个月，尽量保持语义合理：
  /// - 如果当前为 31 日，目标月没有 31 日，则取该月最后一天；
  static DateTime _subtractMonths(DateTime dt, int months) {
    int y = dt.year;
    int m = dt.month - months;
    while (m <= 0) {
      m += 12;
      y -= 1;
    }
    final day = dt.day;
    final lastDay = _lastDayOfMonth(y, m);
    return DateTime(y, m, day > lastDay ? lastDay : day);
  }

  static int _lastDayOfMonth(int year, int month) {
    final beginningNextMonth =
        (month == 12) ? DateTime(year + 1, 1, 1) : DateTime(year, month + 1, 1);
    final lastDay = beginningNextMonth.subtract(const Duration(days: 1)).day;
    return lastDay;
  }
}
